import { useEffect, useRef, useState } from "react";
import useLatestRef from "./useLatestRef";

export default function useMediaQuery(query: string) {
  const isMountedRef = useRef(false);
  const [media, setMedia] = useState(() => {
    return window.matchMedia(query);
  });
  const [isMatch, setMatch] = useState(media.matches);
  const mediaRef = useLatestRef(media);
  useEffect(() => {
    let _media = mediaRef.current;
    if (isMountedRef.current) {
      _media = window.matchMedia(query);
      setMatch(_media.matches);
      setMedia(_media);
    }
    const onChange = function (e: MediaQueryListEvent) {
      setMatch(e.matches);
    };
    _media.addEventListener("change", onChange);
    if (!isMountedRef.current) {
      isMountedRef.current = true;
    }
    return () => {
      _media.removeEventListener("change", onChange);
    };
  }, [query, mediaRef]);

  return isMatch;
}

export function useIsMobile() {
  return useMediaQuery("(max-width: 768px)");
}
